/*
 * @Author: your name
 * @Date: 2021-04-27 10:24:59
 * @LastEditTime: 2021-09-22 11:49:29
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vueDemo\src\router\index.js
 */
import Vue from 'vue'
import Router from 'vue-router'
import { routes } from './routes'

Vue.use(Router)

function toLogin (to, next) {
  localStorage.setItem('loginFromUrl', to.path)
  next({
    replace: true,
    path: '/operate/login'
  })
}

const router = new Router({
  routes
})

router.beforeEach((to, from, next) => {
  // // console.log(to, from, 'beforeEach')
  try {
    if (to.path !== '/operate/login' && to.path.indexOf('operate') > -1) {
      const token = localStorage.getItem('token')
      if (token) {
        const obj = JSON.parse(decodeURIComponent(token))
        if (Number(obj.time) + 15 * 24 * 60 * 60 * 1000 < new Date().getTime()) {
          toLogin(to, next)
        } else {
          next()
        }
      } else {
        toLogin(to, next)
      }
    } else {
      next()
    }
  } catch (err) {
    // console.log(err)
    toLogin(to, next)
  }
})

export default router
